<script setup lang="ts">
import type { CustomDialogInstance } from '@/types'
import { loadRoleEnergyUnit } from '@/api/modules/point'
import type { TreeInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { copyFromEnergyUnit } from '@/api/modules/applicationModel'

const props = defineProps<{
  modelId: number
}>()
const emits = defineEmits<{
  (e: 'saveSuccess'): void
}>()
const dialogRef = ref<CustomDialogInstance>()
const treeRef = ref<TreeInstance>()
const includeIndicator = ref(false)
const treeData = ref<any>([])
const [loading, setLoading] = useState(false)

async function getTreeData() {
  setLoading(true)
  try {
    const res = await loadRoleEnergyUnit()
    treeData.value = res.data ? res.data.list : []
  }
  finally {
    setLoading(false)
  }
}

function getChecked() {
  const checkedNodes = (treeRef.value?.getCheckedNodes(false, true) ?? []).map(v => ({
    id: v.id,
    parentId: v.parentId,
    name: v.pointName,
    pointCode: v.pointCode,
  }))
  const trees = lists2tree(cloneDeep(checkedNodes))
  const recursive = (array: any[]) => {
    const ret: any[] = []
    for (const tree of array) {
      ret.push({
        name: tree.name,
        pointCode: tree.pointCode,
        children: tree.children ? recursive(tree.children) : [],
      })
    }
    return ret
  }

  return recursive(trees)
}

async function clickSave(done?: () => void) {
  const nodeList = getChecked()
  console.log(nodeList)
  try {
    await copyFromEnergyUnit(props.modelId, includeIndicator.value, nodeList)
    done?.()
    close()
    ElMessage.success('保存成功')
    emits('saveSuccess')
  }
  catch (e) {
    console.warn(e)
    done?.()
  }
}
async function onOpen() {}
async function open() {
  await getTreeData()
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="从用能单元复制" width="400px" no-max-height
    @open="onOpen"
    @confirm="clickSave"
  >
    <template #header>
      <ElCheckbox v-model="includeIndicator">
        包含下级指标信息
      </ElCheckbox>
    </template>
    <div v-loading="loading" class="h-sm overflow-auto">
      <ElTree
        ref="treeRef"
        :data="treeData"
        show-checkbox
        node-key="pointCode"
        default-expand-all
        :props="{
          label: 'pointName',
          children: 'children',
        }"
      >
        <template #default="{ node }">
          <div
            class="custom-tree-node flex flex-1 items-center"
          >
            <span>{{ node.label }}</span>
          </div>
        </template>
      </ElTree>
    </div>
  </CustomDialog>
</template>
